package it.pecuswap.backend.delegate;

import it.pecuswap.backend.entities.User;
import it.pecuswap.backend.exceptions.DelegateException;
import it.pecuswap.backend.intefaces.PecuswapServiceDelegateInteface;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

/**
 * The Class PecuswapServiceDelegateImpl.
 *
 */
public class PecuswapServiceDelegateImpl implements PecuswapServiceDelegateInteface {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = Logger
    .getLogger(PecuswapServiceDelegateImpl.class);

    /** The entity manager. */
    @PersistenceContext(unitName = "pecuswapDatabase")
    private EntityManager entityManager;

    /**
     * Instantiates a new Pecuswap Service delegate impl.
     * 
     * @param entityManager
     *            the entity manager
     */
    public PecuswapServiceDelegateImpl(EntityManager entityManager) {
    	super();
    	this.entityManager = entityManager;
    }

    /**
     * Gets the entity manager.
     * 
     * @return the entity manager
     */
    public EntityManager getEntityManager() {
    	return this.entityManager;
    }

    /**
     * Sets the entity manager.
     * 
     * @param entityManager
     *            the new entity manager
     */
    public void setEntityManager(EntityManager entityManager) {
    	this.entityManager = entityManager;
    }

    /*
     *  Find User By user id
     * 
     */
    //@Override
    public User findUserByUserName(String userName) throws DelegateException {
		try {
		    User user = null;
		    Query query = this.entityManager.createQuery(
				    "select u from User u "
				    + "where u.userName = ?1").setParameter(1,userName);
		    
		    @SuppressWarnings("unchecked")
			List<User> list = (List<User>) query.getResultList();
		    if (list!=null && list.size() == 1) {
		    	user = list.get(0);
		    	LOGGER.info("user exists: " + user.getUserName());
		    	return user;
		    }if (list!=null && list.size() > 1) {
		    	LOGGER.error("user duplicate: "+ userName);
		    	return null;
		    } else{
		    	LOGGER.info("user not exists: "+ userName);
		    	return null;
		    }
			
		} catch (Exception e) {
		    LOGGER.error("errore nel metodo findUserByUserName");
		    throw new DelegateException(e.getMessage(), e);
		}
    }
    
    

    // Padding a destra
    /**
     * Pad right.
     * 
     * @param s
     *            the s
     * @param n
     *            the n
     * @return the string
     */
    private String padRight(String s, int n) {
    	return String.format("%1$-" + n + "s", s);
    }

    // Padding a sinistra
    /**
     * Pad left.
     * 
     * @param s
     *            the s
     * @param n
     *            the n
     * @return the string
     */
    private String padLeft(String s, int n) {
    	return String.format("%1$#" + n + "s", s);
    }

        
    /**
     * Gets the next sequence.
     *
     * @param seq the seq
     * @return the next sequence
     * @throws DelegateException the delegate exception
     */
    private int getNextSequence(String seq)
    throws DelegateException {
	BigDecimal count = new BigDecimal(0);
	try {
	    Query query = this.entityManager.createNativeQuery("select rece."+seq+".nextval from  dual");
	    count = (BigDecimal) query.getResultList().get(0);
	    if (count != null)
		return count.intValue();
	    else
		return 0;
	} catch (NoResultException nre) {
	    LOGGER.warn("getNextSequence return no Results");
	    return 0;
	} catch (Exception e) {
	    LOGGER.error("errore nel metodo getNextSequence seq="
		    + seq);
	    throw new DelegateException(e.getMessage(), e);
	}
    }
}
